package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.json.JSONObject;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

import com.google.gson.Gson;
import com.mob.MobSDK;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.activity.RegisterActivity.MyHandler;
import com.ycsj.goldmedalnewconcept.bean.AttResponse;
import com.ycsj.goldmedalnewconcept.bean.CodeResponse;
import com.ycsj.goldmedalnewconcept.bean.ForgetPasswordResponse;
import com.ycsj.goldmedalnewconcept.bean.LoginResponse;
import com.ycsj.goldmedalnewconcept.bean.RegisterResponse;
import com.ycsj.goldmedalnewconcept.constant.Constant;











import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

//重置密码
public class ForgetPasswordActivity extends Activity implements OnClickListener {

	private String account = "";
	private String password1;
	private String password2;
	private String code;
	private String role;
	private ImageView img_back;
	private TextView txt_title;
	private TextView tv_getcode;
	private TextView tv_ok;
	private EditText et_user;
	private EditText et_password1;
	private EditText et_password2;
	private EditText et_code;
	private EventHandler eventHandler;
	private MyHandler mhandler;
	private static final int CODE_ING = 1; // 已发送，倒计时
	private static final int CODE_REPEAT = 2; // 重新发送
	private static final int SMSDDK_HANDLER = 3; // 短信回调
	private int TIME = 300;// 倒计时60s
	private Intent intent;
	private String sms_id;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_forgetpassword);
		mhandler = new MyHandler();
		intent = getIntent();
		role = intent.getStringExtra("role");
		initView();
		initData();
		setListener();
		initSDK();
	}

	// 初始化SMSSDK
	private void initSDK() {
//		SMSSDK.initSDK(this, "1c0fb7d169430",
//				"e0959918dc71b61b493927d6e8f67ab4");
//		MobSDK.init(this, "1c0fb7d169430", "e0959918dc71b61b493927d6e8f67ab4");
		
		eventHandler = new EventHandler() {
			@Override
			public void afterEvent(int event, int result, Object data) {
				Message msg = new Message();
				msg.arg1 = event;
				msg.arg2 = result;
				msg.obj = data;
				msg.what = SMSDDK_HANDLER;
				handler.sendMessage(msg);
			}
		};
		// 注册回调监听接口
//		SMSSDK.registerEventHandler(eventHandler);
	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case CODE_ING:// 已发送,倒计时
				tv_getcode.setText("重新发送(" + --TIME + "s)");
				break;
			case CODE_REPEAT:// 重新发送
				tv_getcode.setText("获取验证码");
				tv_getcode.setClickable(true);
				TIME = 300;
				break;
			case SMSDDK_HANDLER:
				int event = msg.arg1;
				int result = msg.arg2;
				Object data = msg.obj;
				// 回调完成
				if (result == SMSSDK.RESULT_COMPLETE) {
					// 验证码验证成功
					if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {

						
						
						
						
						
						
//						forgetPassword(); // 重置密码
						
						
						
						
						
						
						
						
						
					}
					// 已发送验证码
					else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
//						Toast.makeText(getApplicationContext(), "验证码已经发送至您的手机",
//								Toast.LENGTH_SHORT).show();
					} else {
						((Throwable) data).printStackTrace();
					}
				}
				if (result == SMSSDK.RESULT_ERROR) {
					try {
						Throwable throwable = (Throwable) data;
						throwable.printStackTrace();
						JSONObject object = new JSONObject(
								throwable.getMessage());
						String des = object.optString("detail"); // 错误描述
						int status = object.optInt("status");	 // 错误代码
						if (status > 0 && !TextUtils.isEmpty(des)) {
							Toast.makeText(getApplicationContext(), des,
									Toast.LENGTH_SHORT).show();
							return;
						}
					} catch (Exception e) {
						// do something
					}
				}
				break;
			}
		}
	};

	public void onResume() {
		super.onResume();
	}

	public void onPause() {
		super.onPause();
	}

	private void initView() {
		img_back = (ImageView) findViewById(R.id.img_back);
		txt_title = (TextView) findViewById(R.id.txt_title);
		tv_ok = (TextView) findViewById(R.id.tv_ok);
		et_user = (EditText) findViewById(R.id.et_user);
		et_password1 = (EditText) findViewById(R.id.et_password1);
		et_password2 = (EditText) findViewById(R.id.et_password2);
		tv_getcode = (TextView) findViewById(R.id.tv_getcode);
		et_code = (EditText) findViewById(R.id.et_code);

	}

	private void setListener() {
		img_back.setOnClickListener(this);
		tv_ok.setOnClickListener(this);
		tv_getcode.setOnClickListener(this);

	}

	private void initData() {
		img_back.setVisibility(img_back.VISIBLE);
		txt_title.setText("重置密码");

	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.img_back: // 返回
			finish();
			break;
		case R.id.tv_getcode: // 获取验证码
			account = et_user.getText().toString().trim();
			boolean isphone = isChinaPhoneLegal(account); // 正则表达式判断号码
			if ("".equals(account)) {
				Toast.makeText(getBaseContext(), "手机号码不能为空", 0).show();
				return;
			} else if (!isphone) {
				Toast.makeText(getBaseContext(), "请输入正确的手机号码", 0).show();
				return;
			}
			
			
//			SMSSDK.getVerificationCode("86", account);
			
			//获取验证码
			getCode();
			
			
			tv_getcode.setClickable(false);
		

			break;
		case R.id.tv_ok: // 确认重置
			password1 = et_password1.getText().toString().trim();
			password2 = et_password2.getText().toString().trim();
			code = et_code.getText().toString().trim();
			int passwordlenth = password1.length();

			if (password1.equals("") || password2.equals("")) {
				Toast.makeText(getBaseContext(), "密码不能为空", 0).show();
				return;
			} else if (passwordlenth < 6) {
				Toast.makeText(getBaseContext(), "请设置6位以上的密码", 0).show();
				et_password1.setText("");
				et_password2.setText("");
				et_password1.requestFocus();
				return;
			} else if (!password1.equals(password2)) {
				Toast.makeText(getBaseContext(), "两次输入的密码不一致", 0).show();
				et_password1.setText("");
				et_password2.setText("");
				et_password1.requestFocus();
				return;
			} else if ("".equals(code)) {
				Toast.makeText(getBaseContext(), "请输入短信验证码", 0).show();
				et_code.requestFocus();
				return;
			}else if("".equals(account)){
				Toast.makeText(getBaseContext(), "请获取验证码", 0).show();
				return;
				
			}
			
			if(!isPassword(password1)){
				Toast.makeText(getBaseContext(), "密码只支持6~20位字母与数字的组合", 0).show();
				return;
			}
			
			if(!isPassword(password2)){
				Toast.makeText(getBaseContext(), "密码只支持6~20位字母与数字的组合", 0).show();
				return;
			}
			
			
//			SMSSDK.submitVerificationCode("86", account, et_code.getText()
//					.toString());// 对验证码进行验证
			//对验证码进行验证
			submitCode(code);
			
			
			
			
			break;
		}

	}

	private boolean isPassword(String password2) {
		// TODO Auto-generated method stub
		String regExp = ("^[a-zA-Z0-9]{6,20}+$");
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(password2);
		return m.matches();
		
	}

	//对验证码进行验证
	private void submitCode(String code) {
		
		OkHttpClient mOkHttpClient = new OkHttpClient();
//		 mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "7");		
		builder.add("c", account);		//账号
		builder.add("role", role);		
		builder.add("sms_id", "0");		
		builder.add("code", code);		
		Request request = new Request.Builder()
				.url(Constant.SERVER_URL + "AccountMsg")
				.post(builder.build()).build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络错误", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				
				// 解析Json数据，保存登录状态及身份信息
				Gson gson = new Gson();
				String json = arg0.body().string();
				Log.e("test", "json"+json);
				final AttResponse fromJson = gson.fromJson(json,
						AttResponse.class);
				
				if(fromJson!=null){
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							if("-1".equals(fromJson.state)){
								//没有待验证的验证码数据，需要重新发送新的验证码
								Toast.makeText(getBaseContext(), "验证码错误", 0)
								.show();
							}else if("1".equals(fromJson.state)){
								//通过
								
								forgetPassword(); // 重置密码
								
							}else if("2".equals(fromJson.state)){
								//验证码不一致（内容比对不一致）
								
								Toast.makeText(getBaseContext(), "验证码不一致", 0)
								.show();
							}else if("3".equals(fromJson.state)){
								// 验证码失效（未在发送验证码后5分钟内验证）
								
								Toast.makeText(getBaseContext(), "验证码失效，请重新发送", 0)
								.show();
							}
						}
					});
				}
			}
		});
	}

	//获取验证码
	private void getCode() {
		
				OkHttpClient mOkHttpClient = new OkHttpClient();
//				 mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
				FormEncodingBuilder builder = new FormEncodingBuilder();
				builder.add("type", "1");		
				builder.add("c", account);		//账号
				builder.add("role", role);		
				Request request = new Request.Builder()
//						.url("192.168.0.198:8888/ycsj_platform/" + "FilterMsg")
						.url(Constant.SERVER_URL + "FilterMsg")
						.post(builder.build()).build();
				mOkHttpClient.newCall(request).enqueue(new Callback() {
					

					@Override
					public void onFailure(Request arg0, IOException arg1) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								Toast.makeText(getBaseContext(), "网络错误", 0)
										.show();
							}
						});
					}

					@Override
					public void onResponse(Response arg0) throws IOException {
						
						// 解析Json数据，保存登录状态及身份信息
						Gson gson = new Gson();
						String json = arg0.body().string();
						Log.e("test", "json"+json);
						final CodeResponse fromJson = gson.fromJson(json,
								CodeResponse.class);
						
						if(fromJson!=null){
							
							sms_id = fromJson.sms_id;
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									if("0".equals(fromJson.sms_state)){
										Toast.makeText(getBaseContext(), "验证码已发送至您的手机", 0)
										.show();
										new Thread(new Runnable() {
											@Override
											public void run() {
												for (int i = 300; i > 0; i--) {
													handler.sendEmptyMessage(CODE_ING);
													if (i <= 0) {
														break;
													}
													try {
														Thread.sleep(1000);
													} catch (InterruptedException e) {
														e.printStackTrace();
													}
												}
												handler.sendEmptyMessage(CODE_REPEAT);
											}
										}).start();
										
										
									}else if("-1".equals(fromJson.sms_state)){
										Toast.makeText(getBaseContext(), "发送失败，请联系客服", 0)
										.show();
									}else if("-2".equals(fromJson.sms_state)){
										Toast.makeText(getBaseContext(), "验证码五分钟有效,请查阅短信", 0)
										.show();
									}
								}
							});
						}
					}
				});
		
	}

	public boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
		String regExp = ("^((13[0-9])|(14[0-9])|(15[0-9])|(18[0-9])|(19[0-9])|(16[0-9])|(17[0-9]))\\d{8}$");
//		String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(str);
		return m.matches();
	}

	// 重置密码
	private void forgetPassword() {
		if(role==null||role.equals("")){
			role = "4";
		}
		// TODO Auto-generated method stub
		OkHttpClient mOkHttpClient = new OkHttpClient();
		// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "3");
		builder.add("c", account);
		builder.add("p", password2);
		builder.add("role", role);
		builder.add("platform", "2");

		Request request = new Request.Builder()
				.url(Constant.SERVER_URL + "AccountMsg")
				.post(builder.build()).build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份权限信息
				Gson gson = new Gson();
				String json = arg0.body().string();
				try {
					ForgetPasswordResponse fromJson = gson.fromJson(
							json, ForgetPasswordResponse.class);
					Message message = Message.obtain();
					message.arg1 = 0;
					message.obj = fromJson;
					mhandler.sendMessage(message);
				} catch (Exception e) {
					// TODO: handle exception
					Log.e("test", e.toString());
				}
			
//				{"register":"successful","state":1}{"result":"account is null"}
			}
		});
	}
	
	public class MyHandler extends Handler {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			ForgetPasswordResponse fromJson = (ForgetPasswordResponse) msg.obj;
			if("account is null".equals(fromJson.result)){
				Toast.makeText(getApplicationContext(), "号码未注册，请检查账号是否正确", 1)
						.show();
				
			}
			if ("successful".equals(fromJson.result)) {
				Toast.makeText(getApplicationContext(), "重置成功！用新密码去登录吧", 1)
				.show();
				finish();
//				overridePendingTransition(R.anim.hold,R.anim.fade_out_reg);
			} 
		}
	}
}




